//
//  PhotoBrowseViewController.m
//  12345
//
//  Created by tidoo on 14-3-21.
//  Copyright (c) 2014年 panlisha. All rights reserved.
//

#import "PhotoBrowseViewController.h"
#import "SmilaScroview.h"
#define KIMAGEVIEWTAG   200

@interface PhotoBrowseViewController ()<UIActionSheetDelegate,UIScrollViewDelegate,UIGestureRecognizerDelegate>
{
    NSInteger _imageIndex;
    UIScrollView *_mainSrcrollView;
    
    NSString  *content;
    NSInteger type;
    
    NSInteger saveIndex;
    
    UIImage *_localImage;
    UIImageView *_localImageView;
}
@property(nonatomic,retain)NSMutableArray *imageArray;
@end

@implementation PhotoBrowseViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    //    [Global setStatusBarBackgroundColor:[UIColor clearColor]];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}



- (id)initWithLocalImage:(UIImage *)image
{
    self=[super init];
    if(self)
    {
        _localImage = image;
    }
    return self;
}

-(id)initWithimageArray:(NSMutableArray *)imageArray withIndex:(NSInteger)index withType:(NSInteger)_type
{
    self=[super init];
    if(self)
    {
        self.imageArray=[NSMutableArray arrayWithArray:imageArray];
        _imageIndex = index;
        type = _type;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.view.backgroundColor=[UIColor blackColor];
    
//    self.navigationItem.titleView = [UINavigationItem titleViewForTitle:@"查看大图"];
    self.title = @"查看大图";
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem leftBarButtonItemWithImage:[UIImage imageNamed:@"back.png"] highlighted:[UIImage imageNamed:@"backTap.png"] target:self selector:@selector(back)];
    
//    if (type == KPERSONALPHOTOTAG)
//    {
//        self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightBarButtonItemWithImage:[UIImage imageNamed:@"mshare.png"] highlighted:[UIImage imageNamed:@"mshareDown.png"] target:self selector:@selector(share)];
//    }
//    else if (type == KCOURSEPHOTOTAG)
//    {
//        self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightBarButtonItemWithTitle:@"举报" target:self selector:@selector(reportButtonAction)];
//    }
//    else
//    {
//        self.navigationItem.rightBarButtonItem = nil;
//    }
    
    [self.navigationController.navigationBar setTranslucent:NO];
    

    if (_localImage == nil)  //查看网络
    {
        _mainSrcrollView =[[UIScrollView alloc]initWithFrame:CGRectMake(0,10, kScreenW,kScreenH-54)];
        _mainSrcrollView.contentSize=CGSizeMake(_imageArray.count*kScreenW, kScreenH-120);
        _mainSrcrollView.contentOffset=CGPointMake(_imageIndex*kScreenW, 0);//设置默认的显示
        _mainSrcrollView.pagingEnabled=YES;
        _mainSrcrollView.scrollEnabled=YES;
        _mainSrcrollView.showsHorizontalScrollIndicator=NO;
        _mainSrcrollView.showsVerticalScrollIndicator=NO;
        _mainSrcrollView.delegate=self;
        [self.view addSubview:_mainSrcrollView];
        
        [self initImageViewsInScrollView];//添加图片视图
    }
    else   //查看本地图片
    {
        _localImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
        _localImageView.backgroundColor = [UIColor clearColor];
        _localImageView.image = _localImage;
        _localImageView.contentMode = UIViewContentModeScaleAspectFit;
        [self.view addSubview:_localImageView];
        _localImageView.userInteractionEnabled = YES;
        [_localImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dealTap)]];

//        UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(dealPinch:)];
//        [_localImageView addGestureRecognizer:pinch];
//        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dealPan:)];
//        [_localImageView addGestureRecognizer:pan];
//        
//        UIRotationGestureRecognizer *rotation = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(dealRotation:)];
//        [_localImageView addGestureRecognizer:rotation];
    }
    
}

-(void)dealRotation:(UIRotationGestureRecognizer *)rotation
{
    //rotation表示旋转的角度
    //NSLog(@"%f",rotation.rotation);
    _localImageView.transform = CGAffineTransformMakeRotation(rotation.rotation);
    
}

-(void)dealPan:(UIPanGestureRecognizer *)pan
{
    //获取拖移的位置
    //屏幕上的位置
    CGPoint screenPoint = [pan locationInView:self.view];
    //相对自己的位置
    //CGPoint selfPoint = [pan locationInView:pan.view];
    
    _localImageView.center = screenPoint;
}

- (void)dealTap
{
    [self back];
}

//捏合手势
-(void)dealPinch:(UIPinchGestureRecognizer *)pinch
{
    //获取缩放比例 pinch.scale
    //  设置一个用于缩放的放射变换的对象
    //  实现了缩放的效果
    _localImageView.transform = CGAffineTransformMakeScale(pinch.scale, pinch.scale);
}

//添加图片视图
-(void)initImageViewsInScrollView
{
    for (int i=0; i<_imageArray.count; i++)
    {
//        NSDictionary *dic = [_imageArray objectAtIndex:i];
        
        SmilaScroview * smil = [[SmilaScroview alloc] initWithFrame:CGRectMake(i*kScreenW, 0, kScreenW, _mainSrcrollView.frame.size.height-40)];

        __weak UIActivityIndicatorView *weakS = smil.activityView;
        
        [weakS startAnimating];

        [smil.imageView sd_setImageWithURL:[NSURL URLWithString:[_imageArray objectAtIndex:i]] placeholderImage:KBANNERDEFAULT options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType,NSURL *imageURL)
         {
            [weakS stopAnimating];
            if (error)
            {
                return ;
            }
        }];
        
        smil.imageView .contentMode = UIViewContentModeScaleAspectFit;
        [_mainSrcrollView addSubview:smil];
        smil.tag = 100 + i ;
        
        smil.imageView.tag = 1000 + i;

        //点击返回手势
        UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(back)];
        tapGesture.numberOfTapsRequired=1;
        [smil.imageView addGestureRecognizer:tapGesture];
        
        //常按下载图片
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(dealDownload:)];
        [smil.imageView addGestureRecognizer:longPress];
        
//        if (type == KCOURSEPHOTOTAG)
//        {
//            UILabel *detailLabel=[[UILabel alloc] initWithFrame:CGRectMake(i*SCREEN_WIDTH+10,_mainSrcrollView.frame.size.height-30, 300, 30)];
//            detailLabel.backgroundColor=[UIColor clearColor];
//            NSString *userName=@"";
//            detailLabel.text=[NSString stringWithFormat:@"%@\u3000%@",userName,[dic objectForKey:@"createtime"]];
//            detailLabel.textColor=[UIColor whiteColor];
//            detailLabel.font=[UIFont systemFontOfSize:16];
//            [_mainSrcrollView addSubview:detailLabel];
//        }
    }
}

- (void)dealDownload:(UILongPressGestureRecognizer *)press
{
    saveIndex = press.view.tag - 1000;
    
    if (press.state == UIGestureRecognizerStateBegan)
    {
        UIActionSheet *sheet=[[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil  otherButtonTitles:@"保存到手机",nil];
        sheet.tag = 16;
        [sheet showInView:self.view];
    }
}


//返回按钮和点击手势关联的方法
-(void)back
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

//举报按钮关联的方法
-(void)reportButtonAction
{
//    if (![TDUserInfo getUserInfo])
//    {
//        LoginViewController *login = [[LoginViewController alloc] init];
//        [self.navigationController pushViewController:login animated:YES];
//    }
//    else
//    {
//        UIActionSheet *sheet=[[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil  otherButtonTitles:@"违规信息",@"信息错误",nil];
//        sheet.tag = 15;
//        [sheet showInView:self.view];
//    }
}

//弹出的提示---关联的方法
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 15)
    {
        if(buttonIndex==0)  //违规信息
        {
            content=@"违规信息";
            
            [self report];
        }
        else if(buttonIndex==1) //信息错误
        {
            content=@"信息错误";
            [self report];
        }
        else //取消
        {
            return;
        }
    }
    if (actionSheet.tag == 16)
    {
        if (buttonIndex == 0)
        {
            [self saveImageToMobile];
        }
        else
        {
            return;
        }
    }
}

//保存照片到手机
- (void)saveImageToMobile
{
    UIImageView *imageView = [[UIImageView alloc] init];
    [imageView sd_setImageWithURL:[NSURL URLWithString:_imageArray[saveIndex]] placeholderImage:KBANNERDEFAULT];
    UIImageWriteToSavedPhotosAlbum(imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error == nil)
    {
        [Global showActivityWithView:self.view withText:@"保存成功"];
    }
    else
    {
        [Global showActivityWithView:self.view withText:@"保存失败,请重试"];
    }
}

//举报
-(void)report
{
//    NSDictionary *imageDic=[self.imageArray objectAtIndex:_imageIndex];
//    NSDictionary *securityDic=[Global appNetworkSecurity];
//    NSMutableDictionary *dic=[[NSMutableDictionary alloc] initWithDictionary:securityDic];
//    [dic setObject:[TDUserInfo getUserInfo].ucode forKey:@"ucode"];
//    [dic setObject:[imageDic objectForKey:@"id"] forKey:@"objid"];
//    [dic setObject:@"3" forKey:@"objtype"];
//    [dic setObject:content forKey:@"content"];
//    [dic setObject:@"2" forKey:@"fromapp"];
//
//    NSString *urlString=[NSString stringWithFormat:@"%@%@",REQUEST_URL,KREPORT];
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
//    [manager GET:urlString parameters:dic
//          success:^(AFHTTPRequestOperation *operation,id responseObject)
//     {
//         if ([[responseObject objectForKey:@"data"] isEqualToString:@"true"])
//         {
//             [Global showActivityWithView:self.view withText:@"举报成功"];
//         }
//         else
//         {
//             [Global showActivityWithView:self.view withText:@"举报失败"];
//         }
//     }
//          failure:^(AFHTTPRequestOperation *operation,NSError *error)
//     {
//         DLog(@"error: %@", error);
//     }];
}

static float startContentOffsetX = 0;
static float willEndContentOffsetX = 0;
static float endContentOffsetX = 0;

#pragma mark----UIScrollView--的代理实现
//拖动前的起始坐标
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    startContentOffsetX = scrollView.contentOffset.x;
}
//将要停止前的坐标
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    willEndContentOffsetX = scrollView.contentOffset.x;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    endContentOffsetX = scrollView.contentOffset.x;
    if (endContentOffsetX < willEndContentOffsetX && willEndContentOffsetX < startContentOffsetX)
    {
        //画面从右往左移动，前一页
        _imageIndex--;
    }
    else if (endContentOffsetX > willEndContentOffsetX && willEndContentOffsetX > startContentOffsetX)
    {
        //画面从左往右移动，后一页
        _imageIndex++;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(_mainSrcrollView)
    {
        int page = (_mainSrcrollView.contentOffset.x + _mainSrcrollView.bounds.size.width/2 ) / _mainSrcrollView.bounds.size.width ;
        
        SmilaScroview * smi = (SmilaScroview *)[_mainSrcrollView viewWithTag:100 + page -1];
        if (smi) {
            [smi setZoomScale:1.0];
        }
        smi = (SmilaScroview *)[_mainSrcrollView viewWithTag:100 + page +1];
        if (smi) {
            [smi setZoomScale:1.0];
        }
        
    }
}

// 处理缩放手势
- (void) pinchView:(UIPinchGestureRecognizer *)pinchGestureRecognizer
{
    UIImageView *imageView = (UIImageView *)pinchGestureRecognizer.view ;
    if (pinchGestureRecognizer.state == UIGestureRecognizerStateBegan || pinchGestureRecognizer.state == UIGestureRecognizerStateChanged)
    {
        imageView.transform = CGAffineTransformScale(imageView.transform, pinchGestureRecognizer.scale, pinchGestureRecognizer.scale);
        pinchGestureRecognizer.scale = 1;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
